<?php

class Metacritic {

    public $file = 'data/metacritic/metacritic.tmp';

    public $url = 'http://www.metacritic.com/music/upcomingreleases.shtml';

    public function getReleases() {

        if(!file_exists($this->file)) {

            $f = fopen($_SERVER['DOCUMENT_ROOT'].$this->file, 'w');

            $data = file_get_contents($this->url);

            fwrite($f, $data);
            fclose($f);

        } else {

            $data = file($_SERVER['DOCUMENT_ROOT'].$this->file, FILE_USE_INCLUDE_PATH);
        }

        $tba = false;
        $date = null;

        $result = array();

        foreach($data as $n => $line) {
            if(preg_match('/\<th colspan=\"2\"\>(\d+)\ (january|february|march|april|may|june|july|august|september|october|november|december)(.*)\<\/th\>/i', $line, $m)) {

                $date = strip_tags($m[0]);
                $date = trim(preg_replace('/monday|tuesday|wednesday|thursday|friday|saturday|sunday|&nbsp;/i', '', $date));
                $date = date('Y-m-d', strtotime($date));
            }

            if(strpos($line, 'Anticipated Future Releases') !== false && !empty($date)) {
                $tba = true;
            }

            /*if(preg_match('/\<li\>(.+)\ by\ (.*)\<\/li\>/i', $line, $m)) {

                $release_data = strip_tags($m[0]);

                $release_data = preg_replace('/\[(\d+)\]/', '', $release_data);

                list($release, $artist) = explode('by', $release_data, 2);

                if($tba)
                    $date = date('Y');

                $result[] = array(
                    'date'=>trim($date),
                    'artist'=>trim($artist),
                    'release'=>trim($release));
            }*/
        }

        exit;

        return $result;

    }

}